package com.cn.ccp.servlet;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractRefreshableApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cn.ccp.service.faculty.FacultyService;
import com.cn.ccp.service.faculty.TeachingGroupService;
import com.cn.ccp.service.system.UserService;
import com.cn.ccp.util.CCPContants;

@SuppressWarnings("serial")
public class UploadTeacher extends HttpServlet {
	private Logger log = Logger.getLogger(UploadTeacher.class);
	public final static String DATE_OUTPUT_PATTERNS = "yyyy-MM-dd";  
	private SimpleDateFormat sdf = new  SimpleDateFormat(DATE_OUTPUT_PATTERNS);
	
	private UserService userService ;
	private FacultyService facultyService ;
	private TeachingGroupService teachingGroupService ;
	
	
	public void getStudentService(HttpServletRequest request){
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());//
		 //在servlet中读取applicationContext.xml
		 AbstractRefreshableApplicationContext ctxs = (AbstractRefreshableApplicationContext) ctx;
		 userService = (UserService)  ctxs.getBean("userService");
		 facultyService = (FacultyService)  ctxs.getBean("facultyService");
		 teachingGroupService = (TeachingGroupService)  ctxs.getBean("teachingGroupService");
	}
	
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		getStudentService(request);
		String uid = request.getParameter("uid");
		String savePath = CCPContants.SYS_PATH+"files"+File.separator + "teachers" + File.separator + uid + File.separator;
		File f1 = new File(savePath);
		log.info(savePath);
		if (!f1.exists()) {
			f1.mkdirs();
		}
		File[] old = f1.listFiles();
		for(File f:old)
			f.delete();
		DiskFileItemFactory fac = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(fac);
		upload.setHeaderEncoding("utf-8");
		List fileList = null;
		try {
			fileList = upload.parseRequest(request);
		} catch (FileUploadException ex) {
			return;
		}
		Iterator<FileItem> it = fileList.iterator();
		String name = "";
		String extName = "";
		
		while (it.hasNext()) {
			FileItem item = it.next();
			if (!item.isFormField()) {
				name = item.getName();
				long size = item.getSize();
				String type = item.getContentType();
				log.info(size + " " + type);
				if (name == null || name.trim().equals("")) {
					continue;
				}
				//扩展名格式：  
				if (name.lastIndexOf(".") >= 0) {
					extName = name.substring(name.lastIndexOf("."));
				}
				File file = null;
				do {
					//生成文件名：
					name = UUID.randomUUID().toString();
					file = new File(savePath + name + extName);
				} while (file.exists());
				File saveFile = new File(savePath + name + extName);
				try {
					item.write(saveFile);
				} catch (Exception e) {
					e.printStackTrace();
				}
				extName = verifyFile(saveFile);
			}
		}
		response.setCharacterEncoding("utf-8");
		log.info(extName);
		if("".equalsIgnoreCase(extName))
			response.getWriter().print("success");
		else
			response.getWriter().print(extName);
	}
	
	
	
	private String verifyFile(File file){
		Map<String, Integer> facultyNameIdMap = new HashMap<String, Integer>();
    	Map<String, Integer> teacherGroupIdMap = new HashMap<String, Integer>();
		StringBuffer msgBuf = new StringBuffer();
		Sheet sheet;
        Workbook book;
        try{
        	book = Workbook.getWorkbook(file); 
        	sheet = book.getSheet(0);
        	//从第五行开始读取数据，前面四行预留
        	int allLines = sheet.getRows();
        	log.info("-----------------allLines = "+allLines);
        	Set<String> loginName = new HashSet<String>();
        	for(int i=4;i<allLines;i++){
        		boolean checkLoginName = userService.checkLoginNameIsOk(sheet.getCell(1, i).getContents());
        		
        		if(!checkLoginName || loginName.contains(sheet.getCell(1, i).getContents())){//检测登录名是否重复
        			msgBuf.append("登录名【"+sheet.getCell(1, i).getContents()+"】重复，请重新输入！");
        			file.delete();
        			break;
        		}
        		loginName.add(sheet.getCell(1, i).getContents().toString());
        		
        		if("1".equals(sheet.getCell(5, i).getContents()) && "2".equals(sheet.getCell(5, i).getContents()) ){//检测用户性别输入是否合法
        			msgBuf.append("第【"+i+"】行性别数据不是1或2，请重新输入！");
        			file.delete();
        			break;
        		}
        		
        		if("2".equals(sheet.getCell(7, i).getContents()) && "3".equals(sheet.getCell(7, i).getContents()) && "4".equals(sheet.getCell(7, i).getContents())){//检测用户性别输入是否合法
        			msgBuf.append("第【"+i+"】行用户类型数据不是2、3、4，请重新输入！");
        			file.delete();
        			break;
        		}
        		
        		try{
        			sdf.parse(sheet.getCell(9, i).getContents());
        		}catch(Exception e){
        			log.error("get date faile", e);
        			msgBuf.append("第【"+i+"】行出生年月格式有误，请重新输入！");
        			file.delete();
        			break;
        		}
        		try{
        			sdf.parse(sheet.getCell(11, i).getContents());
        		}catch(Exception e){
        			log.error("get date faile", e);
        			msgBuf.append("第【"+i+"】行入学时间格式有误，请重新输入！");
        			file.delete();
        			break;
        		}
        		
        		if("1".equals(sheet.getCell(12, i).getContents()) && "2".equals(sheet.getCell(12, i).getContents()) && "3".equals(sheet.getCell(12, i).getContents())){//检测用户性别输入是否合法
        			msgBuf.append("第【"+i+"】行职称数据不是1、2、3，请重新输入！");
        			file.delete();
        			break;
        		}
        		
        		String faculyName = sheet.getCell(14, i).getContents() ;
        		if(!facultyNameIdMap.containsKey(faculyName)){
        			try {
        				int id = facultyService.getFacultyIdByfacultyName(faculyName);
        				facultyNameIdMap.put(faculyName, id);
					} catch (Exception e) {
						msgBuf.append("第【"+i+"】行输入的学院名称["+faculyName+"]在系统中不存在，请查看系统学院信息后重新输入");
						file.delete();
	        			break;
					}
        		}
        		String teachGroupName = sheet.getCell(15, i).getContents() ;
        		teachGroupName = teachGroupName.replace("，", ",").trim();
        		String[] strs = teachGroupName.split(",");
        		for(String s : strs)
        			if(s != null  && !s.equals("")){
        				if(!teacherGroupIdMap.containsKey(s)){
        					try {
        						int id = teachingGroupService.showBeanByName(s.trim()); 
            					teacherGroupIdMap.put(s, id);
							} catch (Exception e) {
								msgBuf.append("第【"+i+"】行输入的教研组名称["+s+"]在系统中不存在，请核对后重新输入");
								file.delete();
			        			break;
							}
        				}
        			}
        	}
        	
        	
        }catch(Exception e){
        	log.error("read file failed : ",e);
        	msgBuf.append("Read the file failed .");
        	file.delete();
        }
        log.info(msgBuf);
        return msgBuf.toString();
	}
	
	
	
	
}
